<template>
  <div class="add-order-product-view">

    <div style="display: flex;margin-bottom: 10px">

      <el-button
        class="main-btn"
        size="small"
        type="primary"
        @click="addClick"
      >增加行</el-button>

      <el-button
        class="main-btn delete-btn"
        size="small"
        @click="deleteClick"
      >全部删除</el-button>

      <div style="margin-left: 10px;display: flex;align-items: center">
        <span style="font-size: 18px">订单预估总金额</span>

        <span style="color: orange;margin: 0 5px">{{ dealPrice() }}元</span>

        <span v-if="datas.order.orderType == 1">(按产品市场价计算)</span>
        <span v-else-if="datas.order.orderType == 2">(按产品终端价计算)</span>
        <span v-else>(按产品交易价计算)</span>
      </div>

    </div>

    <el-table
            :key="defaultKey"
      border
      :data="datas.orderDetail"
      :cell-style="cellStyle"
    >
      <el-table-column type="index" width="55" fixed="left"/>
      <el-table-column header-align="center" align="center" label="产品名称" fixed="left" min-width="150px" show-overflow-tooltip>
        <template #default="scope">
          <el-select
            v-if="!scope.row.productId"
            v-model="scope.row.productId"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteMethod"
            :loading="loading"
            placeholder="请选择产品"
            @change="(val) => {productChange(val,scope)}"
          >
            <el-option
              v-for="item in products"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            />
          </el-select>
          <span v-else>{{ scope.row.productPopularName }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="商品名" prop="productName" width="100" show-overflow-tooltip/>
      <el-table-column header-align="center" align="center" label="包装规格" prop="packSpecs" width="100" show-overflow-tooltip/>
      <el-table-column header-align="center" align="center" label="生产厂家" prop="producer" min-width="100" show-overflow-tooltip/>
      <el-table-column v-if="datas.order.orderType == 1" header-align="center" align="center" label="市场价(元)" width="100px">
        <template #default="scope">
          {{ scope.row.terminalPrice }}
        </template>
      </el-table-column>
      <el-table-column v-if="datas.order.orderType == 3" header-align="center" align="center" label="交易价(元)" width="150px">
        <template #default="scope">
          <trading-popover :ref="(el)=>{setRefs(el,scope)}" :sell-mode="datas.order.agentType" :props-agent="{agentId:datas.order.agentId,productId:scope.row.productId}"
                               @confirm="(val)=>{tradConfirm(val,scope)}">
            <el-select v-model="scope.row.tradePrice" placeholder="请选择交易价" :disabled="!(scope.row.productId > 0)" style="width: 100%" @focus="openTrad(scope)">
              <template #empty />
            </el-select>
          </trading-popover>
        </template>
      </el-table-column>
      <el-table-column v-if="datas.order.orderType == 4" header-align="center" align="center" label="交易价(元)" prop="tradePrice" width="100px"/>
      <el-table-column header-align="center" align="center" label="数量" min-width="200px">
        <template #default="scope">

          <el-input v-model.number="scope.row.number" clearable placeholder="请输入数量" @blur="()=>{numBlur(scope)}">
            <template #append>
              <el-select v-model="scope.row.unitType" style="width: 80px;" placeholder="请选择" @change="(val) => {unitChange(val,scope)}">
                <el-option v-for="item in scope.row.unitOption" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </template>
          </el-input>

        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="按计价单位数量" width="150px">
        <template #default="scope">
          <span v-if="scope.row.putNumber">{{ scope.row.putNumber }}{{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="datas.order.orderType == 2" header-align="center" align="center" label="终端价(元)" prop="terminalPrice" width="100px"/>
      <el-table-column header-align="center" align="center" label="小计(元)">
        <template #default="scope">
          {{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column v-if="datas.order.orderType == 2" header-align="center" align="center" label="营销模式" width="100">
        <template #default="scope">
          <span v-if="scope.row.productId && !scope.row.agentAttribute">终端直销</span>
          <span v-else-if="scope.row.agentAttribute == 1">区域招商</span>
          <span v-else-if="scope.row.agentAttribute == 2">精细招商</span>
        </template>
      </el-table-column>
      <el-table-column v-if="datas.order.orderType == 2" header-align="center" align="center" label="代理名称" prop="agentName" width="150px" show-overflow-tooltip/>
      <el-table-column v-if="datas.order.orderType == 2" header-align="center" align="center" label="交易价(元)" prop="tradePrice" width="100px"/>
      <el-table-column header-align="center" align="center" label="操作" width="70px" fixed="right">
        <template #default="scope">
          <el-button type="text" class="delete-text-btn" @click="onDelete(scope)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

  </div>
</template>

<script>

import {getProductName} from "../../../../../../../utils/commonFun";
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, reactive, toRefs, onMounted} from 'vue'

export default defineComponent({
  name: 'AddProduct',
  emits:['onDelete'],
  components:{
    tradingPopover:defineAsyncComponent(
            () => import('../../modules/tradingPopover.vue')
    )
  },
  props: {
    datas: {
      type: Array,
      default: []
    }
  },
  setup(props, { emit }) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')

    var data = reactive({
      products: [],
      nuitData: [],
      loading: false,
      refs:{},
      defaultKey:0,
    })

    onMounted(() => {
      data.defaultKey ++
    })

    const setRefs = (el, scope) => {
      data.refs[scope.$index] = el
    }

    // 打开交易价弹框
    const openTrad = (scope) => {
      data.refs[scope.$index].openPopover();
    };

    const tradConfirm = (val,scope) => {
      console.log(222222,val)
      props.datas.orderDetail[scope.$index].tradePrice = val.tradePrice
      props.datas.orderDetail[scope.$index].agentProductId = val.id

      numBlur(scope)
    }

    const remoteMethod = (query) => {
      data.products = []
      if (props.datas.order.orderType == 1) {
        if (!props.datas.order.distributeId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择配送商',
          })
          return
        }
      } else if (props.datas.order.orderType == 2) {
        if (!props.datas.order.terminalId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择终端',
          })
          return
        }
      } else if (props.datas.order.orderType == 3) {
        if (!props.datas.order.agentId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择代理商',
          })
          return
        }
      } else if (props.datas.order.orderType == 4) {
        if (!props.datas.order.sellerId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择商销客户',
          })
          return
        }
      }

      data.loading = true

      const a = { ...props.datas.order }
      if (query) {
        a.productName = query
      }

      api.order.GET_ORDER_PRODUCT_LIST(a).then(res => {
        if (!res.code && res.data) {
          res.data.list.forEach(item => {
            item.name = getProductName(item);
            // if (item.productName){
            //   item.name = item.productName + '-' + item.productPopularName + '-' + item.packSpecs
            // }else {
            //   item.name = item.productPopularName + '-' + item.packSpecs
            // }

          })
          data.products = res.data.list

          data.loading = false
        }
      })
    }

    const baseChange = () => {
      data.products = []
    }

    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }

    const dealPrice = () => {
      let price = 0

      props.datas.orderDetail.forEach(item => {
        if (item.totalAmount) {
          price += item.totalAmount
        }
      })

      const str = price.toFixed(2)

      return Number(str)
    }

    const productChange = (val, scope) => {
      if (val) {
        const idx = props.datas.orderDetail.findIndex(a => a.productId == val)

        if (idx != -1 && idx != scope.$index) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '产品已添加，请选择其他产品',
          })
          props.datas.orderDetail[scope.$index].productId = ''
        } else {
          const index = data.products.findIndex(a => a.productId == val)
          if (index != -1) {
            // let row = props.datas.orderDetail[scope.$index]
            const pro = { ...data.products[index] }
            pro.unitType = 'sellUnit'
            pro.unit = currentInstance.proxy.getLabel('sell_unit', pro.sellUnit)
            pro.packNum = 1
            pro.number = ''
            pro.unitOption = [
              {
                label: currentInstance.proxy.getLabel('sell_unit', pro.sellUnit),
                id: 'sellUnit',
                packNum: 1
              }
            ]
            if (!pro.tradePrice){
              pro.tradePrice = ''
            }
            if (pro.mPackUnit) {
              pro.unitOption.push({
                label: currentInstance.proxy.getLabel('sell_unit', pro.mPackUnit),
                id: 'mPackUnit',
                packNum: pro.mPackNum
              })
            }
            if (pro.lPackUnit) {
              pro.unitOption.push({
                label: currentInstance.proxy.getLabel('sell_unit', pro.lPackUnit),
                id: 'lPackUnit',
                packNum: pro.lPackNum
              })
            }
            if (props.datas.order.orderType == 1) {
              pro.terminalPrice = pro.marketPrice
            } else {
              pro.terminalPrice = pro.terminalPrice
            }

            // for (let key in pro){
            //     row[key] = pro[key]
            // }

            props.datas.orderDetail[scope.$index] = pro
            if (props.datas.order.orderType == 3){
              getTradPrice(scope.$index,pro)
            }

          }
        }
      }
    }

    const getTradPrice = (index,pro) => {
      let pData = {
        page:1,
        pageSize:100,
        agentProductStatus:'2',
        agentId:props.datas.order.agentId,
        productId:pro.productId
      }
      api.signedAgent.AGENT_PRODUCT_LIST(pData).then((res) => {
        if (!res.code && res.data) {
          if (res.data.list && res.data.list.length == 1) {
            props.datas.orderDetail[index].tradePrice = res.data.list[0].tradePrice
            props.datas.orderDetail[index].agentProductId = res.data.list[0].id
          }

        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const tradPriceChange = () => {

    }

    const unitChange = (val, scope) => {
      const pro = props.datas.orderDetail[scope.$index]
      if (val) {
        const index = pro.unitOption.findIndex(a => a.id == val)
        if (index != -1) {
          pro.unit = pro.unitOption[index].label
          pro.packNum = pro.unitOption[index].packNum
          if (pro.number) {
            pro.putNumber = pro.number * pro.packNum
            if (pro.putNumber) {
              if (props.datas.order.orderType == 3 || props.datas.order.orderType == 4){
                const str = Number(pro.putNumber * pro.tradePrice).toFixed(2)
                pro.totalAmount = Number(str)
              }else {
                const str = Number(pro.putNumber * pro.terminalPrice).toFixed(2)
                pro.totalAmount = Number(str)
              }
            }
          }
        }
      } else {
        pro.putNumber = 0
        pro.totalAmount = 0
      }
    }

    const numBlur = (scope) => {
      const pro = props.datas.orderDetail[scope.$index]
      if (pro.number) {
        pro.putNumber = pro.number * pro.packNum
        if (pro.putNumber) {
          if (props.datas.order.orderType == 3 || props.datas.order.orderType == 4){
            const str = Number(pro.putNumber * pro.tradePrice).toFixed(2)
            pro.totalAmount = Number(str)
          }else {
            const str = Number(pro.putNumber * pro.terminalPrice).toFixed(2)
            pro.totalAmount = Number(str)
          }

        }
      } else {
        pro.putNumber = 0
        pro.totalAmount = 0
      }
    }

    const addClick = () => {
      if (props.datas.order.orderType == 1) {
        if (!props.datas.order.distributeId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先选择配送商',
          })

          return
        }
      } else if (props.datas.order.orderType == 2) {
        if (!props.datas.order.terminalId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先选择终端',
          })

          return
        }
      } else if (props.datas.order.orderType == 3) {
        if (!props.datas.order.agentId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先选择代理商',
          })

          return
        }
      } else if (props.datas.order.orderType == 4) {
        if (!props.datas.order.sellerId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择商销客户',
          })
          return
        }
      }
      if (props.datas.order.isSplit == 2) {
        if (props.datas.order.agentType != 'direct' && !props.datas.order.agentId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先选择代理商',
          })

          return
        }
      }
      props.datas.orderDetail.push({
        productId: '',
        putNumber: '', // 下单数量
        unit: '', // 单位
        unitType: '', // 单位类型 1 机型单位  2 小包装 3 大包装
        minSaleNumber: '',
        minSaleUnit: '',
        terminalPrice: '',
        totalAmount: '',
        tradePrice: '',
        agentId: '',
        unitOption: []
      })
    }

    const deleteClick = () => {
      // props.list = [];
      emit('onDelete')
    }

    const onDelete = (scope) => {
      if (scope.row.id) {
        props.datas.deleteDetailIds.push(scope.row.id)
      }
      props.datas.orderDetail.splice(scope.$index, 1)
    }

    const validate = () => {
      if (!props.datas.orderDetail || !props.datas.orderDetail.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请添加产品信息',
        })
        return false
      } else {
        for (let i = 0; i < props.datas.orderDetail.length; i++) {
          const item = props.datas.orderDetail[i]
          if (!item.productId) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请选择产品',
            })
            return false
          }
          if (!item.putNumber) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请输入发货数量',
            })
            return false
          }
          if (props.datas.order.orderType == '3'){
            if (!item.tradePrice || !item.agentProductId) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: '请选择交易价',
              })
              return false
            }
          }
        }

        return true
      }
    }

    const getData = () => {
      const a = { ...props.datas.order }
      api.order.GET_ORDER_PRODUCT_LIST(a).then(res => {
        if (!res.code && res.data) {
          res.data.list.forEach(item => {
            if (item.productName){
              item.name = item.productName + '-' + item.productPopularName + '-' +  item.packSpecs
            }else{
              item.name = item.productPopularName + '-' + item.packSpecs
            }

          })
          data.products = res.data.list

          data.loading = false
        }
      })
    }

    return {
      ...toRefs(data),

      addClick,
      deleteClick,
      cellStyle,
      onDelete,
      remoteMethod,
      productChange,
      unitChange,
      numBlur,
      dealPrice,
      validate,
      getData,
      baseChange,
      tradPriceChange,
      getTradPrice,
      setRefs,
      openTrad,
      tradConfirm,
    }
  }
})
</script>

<style scoped>

</style>
